package com.dvt.faceScan;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.baidu.idl.face.platform.FaceConfig;
import com.baidu.idl.face.platform.FaceEnvironment;
import com.baidu.idl.face.platform.FaceSDKManager;
import com.baidu.idl.face.platform.FaceStatusEnum;
import com.baidu.idl.face.platform.LivenessTypeEnum;
import com.baidu.idl.face.platform.ui.FaceDetectActivity;
import com.dvt.faceScan.httpUntil.MyThread;
import com.dvt.faceScan.httpUntil.DataUtil;
import com.dvt.faceScan.httpUntil.XmlRpcUtils;
import com.dvt.faceScan.widget.Config;
import com.dvt.faceScan.widget.DefaultDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;


/**
 * Created by XGJ on 2018/3/16.
 */

public class FaceActivity extends FaceDetectActivity {
    List livenessList = new ArrayList();
    private DefaultDialog mDefaultDialog;
    private String tokenStirng;
    private HashMap<String,String> Img;
    private String ID;  //判断注册还是识别
    private String dates; //当前时间
    private String companyID; // 公司id
    private String faceID; //扫描注册用的ID，为了注册人脸库
    private String name;
    private String  empID; // 识别人脸用的ID 人脸库返回的uid就是员工的ID
    private int  _companyID;
    private String sigin_in;
    private int intSignData_ID=0;  //是签到数据id
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Intent in = getIntent();
        ID = in.getStringExtra("id");
        faceID = in.getStringExtra("empID");
        sigin_in = in.getStringExtra("in");

        requestToken(); //获取token
        setmInitView();

    }
    //活体检测
    private  void setmInitView(){
        FaceConfig config= FaceSDKManager.getInstance().getFaceConfig();
        livenessList.add(LivenessTypeEnum.Mouth);
        livenessList.add(LivenessTypeEnum.Eye);
        livenessList.add(LivenessTypeEnum.HeadDown);
        livenessList.add(LivenessTypeEnum.HeadLeft);
        livenessList.add(LivenessTypeEnum.HeadRight);
        livenessList.add(LivenessTypeEnum.HeadUp);
//        config.setLivenessTypeList(livenessList);//设置活体检测类型
//        config.setLivenessRandom(false);
        config.setBlurnessValue(FaceEnvironment.VALUE_BLURNESS);
        config.setBrightnessValue(FaceEnvironment.VALUE_BRIGHTNESS);
        config.setCropFaceValue(FaceEnvironment.VALUE_CROP_FACE_SIZE);
        config.setHeadPitchValue(FaceEnvironment.VALUE_HEAD_PITCH);
        config.setHeadYawValue(FaceEnvironment.VALUE_HEAD_YAW);
        config.setHeadRollValue(FaceEnvironment.VALUE_HEAD_ROLL);
        config.setMinFaceSize(FaceEnvironment.VALUE_MIN_FACE_SIZE);
        config.setNotFaceValue(FaceEnvironment.VALUE_NOT_FACE_THRESHOLD);
        config.setOcclusionValue(FaceEnvironment.VALUE_OCCLUSION);
        config.setCheckFaceQuality(true);
        config.setLivenessRandomCount(2);
        config.setFaceDecodeNumberOfThreads(2);
        FaceSDKManager.getInstance().setFaceConfig(config);
    }

    @Override
    public void onDetectCompletion(FaceStatusEnum status, String message, HashMap<String, String> base64ImageMap) {
        super.onDetectCompletion(status, message, base64ImageMap);
        if (status == FaceStatusEnum.OK && mIsCompletion) {
            if("1".equals(ID)){   //人脸注册
                String DataRegister = FaceRegister.add(base64ImageMap,faceID);
                try{
                    JSONObject jsonObject = new JSONObject(DataRegister);
                    int errorCode = jsonObject.optInt("error_code");
                    Log.d("错误码1",errorCode+"");
                    if(216200 == errorCode){
                        showMessageDialog("提示","图片为空");
                    }else{
                        showMessageDialog("人脸检测","人脸注册成功");
                    }
                }catch (JSONException e){
                    e.printStackTrace();
                }
                Log.d("返回值1",""+ DataRegister);

            }else if("2".equals(ID)){    //人脸识别
                String DataDiscern= FaceDiscern.identify(base64ImageMap);
                try{
                    JSONObject jsonObject = new JSONObject(DataDiscern);
                    int errorCode = jsonObject.optInt("error_code");
                    Log.d("错误码2",errorCode+"");
                    if(216618 == errorCode){
                        showMessageDialog("提示","人脸未注册");
                    }else{
                       String employInfo = DataDiscern;   //人脸库返回数据，包括员工ID。
                        try{
                            JSONObject _employID = new JSONObject(employInfo);
                            JSONArray _employRs = _employID.getJSONArray("result");
                            for(int i=0;i<_employRs.length();i++) {
                                JSONObject job = _employRs.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                 empID = job.getString("uid");
                                Log.d("111",empID);
                            }
                            if(sigin_in.equals("0")){  //签到
                                requestEmployeeDetail();
                            }else{
                                ListSigin_out();      //签退
                            }

                        }catch(JSONException e){
                            e.printStackTrace();
                        }
                    }
                }catch (JSONException e){
                    e.printStackTrace();
                }
            }
        } else if (status == FaceStatusEnum.Error_DetectTimeout || status == FaceStatusEnum.Error_LivenessTimeout || status == FaceStatusEnum.Error_Timeout) {
            showMessageDialog("人脸图像采集", "采集超时");
        }
    }

    //调员工明细接口 （为了拿出公司id）；
    public void requestEmployeeDetail(){
        Callable<String> c = new Callable<String>(){
            @Override
            public String call(){
                int _empID = Integer.parseInt(empID);
                int uid = 1;
                String db = Config.DB;
                String uname = Config.account;
                String pwd = Config.password;
                String odooUrl = Config.baseURL;
                String url = String.format("%s/xmlrpc/2/object", odooUrl);
                String model = Config.hr_employee;
                int action_id = 121;

                Map<String,Object> params = new HashMap<String,Object>();
                params.put("action",action_id);
                Map<String,Object> context = new HashMap<String,Object>();
                context.put("lang", "zh_CN");
                context.put("tz", "Asia/Hong_Kong");
                context.put("uid", uid);
                context.put("params", params);
                Map<String,Object> kwargs = new HashMap<String,Object>();
                kwargs.put("context",context);
                List args = asList(asList(_empID),asList("name","hired_company_id"));
                Map<String,Object> options = new HashMap<String,Object>();
                options.put("kwargs", kwargs);
                options.put("args", args);
                Object requestObj = XmlRpcUtils.getXMLRPC(url, "execute_kw", asList(db, uid, pwd, model,"read",args, kwargs));
                List r =asList((Object[])requestObj);
                for (Object object : r) {
                    Map<String,Object> a = (HashMap)object;
                    name = String.valueOf(a.get("name"));
                    if(!"false".equals(String.valueOf(a.get("hired_company_id")))) {
                        Object[] o = (Object[]) a.get("hired_company_id");
                        Log.d("objeee", o+"");
                        List<Object> ol = asList(o);
                        String str = ol.get(0).toString();
                        _companyID = Integer.parseInt(str);
                    }else{
                        companyID = "";
                    }
                }
                createSigin_in(); //添加一条考勤记录
                return "";
            }
        };

        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(c);
        try{
            String result = future.get(5000, TimeUnit.SECONDS);
            Log.d("request",result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    // 创建一条签到记录
    public void createSigin_in(){
        Callable<String> c = new Callable<String>(){
            @Override
            public String call(){
                int uid = 1;
                int _empID = Integer.parseInt(empID);
                String db = Config.DB;
                String uname = Config.account;
                String pwd = Config.password;
                String model = Config.dris_employee_attendance;
                String odooUrl = Config.baseURL;
                String url = String.format("%s/xmlrpc/2/object", odooUrl);
                int action_id = 683;
                String time_in = "";
                String time_out ="";

                Map<String,Object> params = new HashMap<String,Object>();
                params.put("action",action_id);
                params.put("view_type","form");
                params.put("id",20);
                params.put("menu_id",93);
                Map<String,Object> context = new HashMap<String,Object>();
                context.put("lang", "zh_CN");
                context.put("tz", "Asia/Hong_Kong");
                context.put("uid", uid);
                context.put("params", params);
                Map<String,Object> kwargs = new HashMap<String,Object>();
                kwargs.put("context",context);

                Map<String,Object> argsEmp = new HashMap<String,Object>();
                argsEmp.put("employee_id",_empID); //员工id
                argsEmp.put("hired_company_id",_companyID); //公司id
                argsEmp.put("name",name);  //员工名字
                time_in = DataUtil.timeUtil();
                Log.d("返回值time",""+time_in);
                argsEmp.put("sign_in",time_in);  //签到时间
                List args = asList(argsEmp);

                Map<String,Object> options = new HashMap<String,Object>();
                options.put("kwargs", kwargs);
                options.put("args", args);

                Object requestObj = XmlRpcUtils.getXMLRPC(url, "execute_kw", asList(db, uid, pwd, model,"create",args, kwargs));
                Log.d("返回值签到记录",""+ requestObj);
                //签到成功返回上一页

                if(requestObj == null){
//                    showMessageDialog1s("人脸签到", "人脸签到失败");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(FaceActivity.this, "人脸签到失败", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    });
                }else{
//                    showMessageDialog1s("人脸签到", "人脸签到成功");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(FaceActivity.this, "人脸签到成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    });
                }
                return "";
            }
        };
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(c);
        try{
            String result = future.get(5000, TimeUnit.SECONDS);
            Log.d("request",result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //用员工id和当前时间减24小时拿到最新的一条数据 （search_read）
    public void ListSigin_out(){
        Callable<String> c = new Callable<String>(){
            @Override
            public String call(){
                int uid = 1;
                int _empID = Integer.parseInt(empID);  //员工id =48
                String db = Config.DB;
                String uname = Config.account;
                String pwd = Config.password;
                String model = Config.dris_employee_attendance;
                String odooUrl = Config.baseURL;
                String url = String.format("%s/xmlrpc/2/object", odooUrl);
                int action_id = 683;
                String time_out ="";

                Map<String,Object> params = new HashMap<String,Object>();
                params.put("action",action_id);
                params.put("view_type","form");
                params.put("menu_id",93);

                Map<String,Object> context = new HashMap<String,Object>();
                context.put("lang", "zh_CN");
                context.put("tz", "Asia/Hong_Kong");
                context.put("uid", uid);
                context.put("params", params);

                //获取当前时间
                time_out = DataUtil.dayUtil();
                Log.d("返回值2",""+time_out);

                List args = asList(asList("employee_id","=",_empID),asList("sign_in",">=",time_out));

                Map<String, Object> options = new HashMap<String, Object>();
                options.put("context", context);
                options.put("domain", args);
                options.put("fields", asList("employee_id"));
                options.put("limit", 80);

                Object requestObj = XmlRpcUtils.getXMLRPC(url, "execute_kw", asList(db, uid, pwd, model, "search_read", new ArrayList(),
                        options
                ));
                Log.d("签到list",""+ requestObj);
                List r = asList((Object[]) requestObj);

                for (Object object : r) {
                    Map<String, Object> a = (HashMap) object;
                    String signData_ID = String.valueOf(a.get("id"));
                    intSignData_ID = Integer.parseInt(signData_ID);
                    Log.d("签到signData_ID",""+ signData_ID);
                    Set<String> akeySet = a.keySet();
                    for (String key : akeySet) {
                        Log.d("mmmmmmmm", key + "-->" + a.get(key));
                    }
                }
                if(intSignData_ID != 0){
                    writeSign_out();
                }

                return "";
            }
        };
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(c);
        try{
            String result = future.get(5000, TimeUnit.SECONDS);
            Log.d("request",result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //签退
    public void writeSign_out(){
        Callable<String> c = new Callable<String>(){
            @Override
            public String call(){
                int uid = 1;
                int _empID = Integer.parseInt(empID);  //员工id =48
                String db = Config.DB;
                String uname = Config.account;
                String pwd = Config.password;
                String model = Config.dris_employee_attendance;
                String odooUrl = Config.baseURL;
                String url = String.format("%s/xmlrpc/2/object", odooUrl);
                int action_id = 683;
                String time_out ="";

                Map<String,Object> params = new HashMap<String,Object>();
                params.put("action",action_id);
                params.put("view_type","form");
                params.put("id",20);
                params.put("menu_id",93);

                Map<String,Object> context = new HashMap<String,Object>();
                context.put("lang", "zh_CN");
                context.put("tz", "Asia/Hong_Kong");
                context.put("uid", uid);
                context.put("params", params);

                Map<String,Object> kwargs = new HashMap<String,Object>();
                kwargs.put("context",context);

                //获取当前时间
                Map<String,Object> argsEmp = new HashMap<String,Object>();
                time_out = DataUtil.timeUtil();
                Log.d("时间",""+time_out);
                argsEmp.put("sign_out",time_out);//签退时间

                List args = asList(asList(intSignData_ID),argsEmp);

                Map<String,Object> options = new HashMap<String,Object>();
                options.put("kwargs", kwargs);
                options.put("args", args);

                Object requestObj = XmlRpcUtils.getXMLRPC(url, "execute_kw", asList(db, uid, pwd, model,"write",args, kwargs));
                Log.d("返回值3",""+ requestObj);
                //签到成功返回上一页
                if(requestObj == null){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(FaceActivity.this, "人脸签退成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    });
                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(FaceActivity.this, "人脸签退成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    });
                }
                return "";
            }
        };
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(c);
        try{
            String result = future.get(5000, TimeUnit.SECONDS);
            Log.d("request",result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    private List asList(Object ...a){
        return Arrays.asList(a);
    }

    private void showMessageDialog(String title, String message) {
        if (mDefaultDialog == null) {
            DefaultDialog.Builder builder = new DefaultDialog.Builder(this);
            builder.setTitle(title).
                    setMessage(message).
                    setNegativeButton("确认",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mDefaultDialog.dismiss();
                                    finish();
                                }
                            });
            mDefaultDialog = builder.create();
            mDefaultDialog.setCancelable(true);
        }
        mDefaultDialog.dismiss();
        mDefaultDialog.show();
    }
    @Override
    public void finish() {
        super.finish();
    }
    //获取token
    private  void requestToken(){
        //获取 token
        MyThread myThread = new MyThread();
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Future<String> future = pool.submit(myThread);
        try{
            String access_token = future.get(5000, TimeUnit.SECONDS);
            Config.token = access_token;
            Log.d("token",access_token);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showMessageDialog1s(final String title,  String message) {
        //弹窗框
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                AlertDialog.Builder builder = new AlertDialog.Builder(FaceActivity.this);
//                final AlertDialog alertDialog = builder.setTitle(title).setMessage(message).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        Toast.makeText(FaceActivity.this, message, Toast.LENGTH_SHORT).show();
//                        dialog.dismiss();
//                        finish();  //返回上一层
//                    }
//                }).create();
//                alertDialog.show();
//            }
//        });





    }



}
